package cn.stylefeng.guns.modular.gridsystem.modbus;

import cn.hutool.core.util.ObjectUtil;
import lombok.Data;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

@Data
public class ModbusDeviceLog {

    private int offset = 0;
    private Integer logId;
    private Integer deviceId;
    private Integer gatewayId;
    private Integer errorId;
    private Integer updateDate;

    public List<Short> encode() {
        // Integer logId;
        // Integer deviceId;
        // Integer gatewayId;
        // Integer errorId;
        // Integer updateDate;
        List<Short> data = new ArrayList<>();
        data.add((short) ((logId >> 16) & 0xffff));
        data.add((short) ((logId) & 0xffff));

        data.add((short) ((deviceId >> 16) & 0xffff));
        data.add((short) ((deviceId) & 0xffff));

        data.add((short) ((gatewayId >> 16) & 0xffff));
        data.add((short) ((gatewayId) & 0xffff));

        data.add((short) ((errorId >> 16) & 0xffff));
        data.add((short) ((errorId) & 0xffff));

        if(ObjectUtil.isNotNull(updateDate)){
            data.add((short) ((updateDate >> 16) & 0xffff));
            data.add((short) ((updateDate) & 0xffff));
        }

        return data;
    }

    @Override
    public String toString() {
        return "ModbusDeviceLog{" +
                "offset=" + offset +
                ", logId=" + logId +
                ", deviceId=" + deviceId +
                ", gatewayId=" + gatewayId +
                ", errorId=" + errorId +
                ", updateDate=" + updateDate +
                '}';
    }

    public static void main(String[] args) {
        ModbusDeviceLog log = new ModbusDeviceLog();
        log.setLogId(1);
        log.setDeviceId(2);
        log.setGatewayId(ByteBuffer.wrap("dalian".getBytes()).getInt());
        log.setErrorId(4);
        log.setUpdateDate((int) (System.currentTimeMillis() / 1000));
        System.out.println(log);

        final List<Short> encode = log.encode();

        System.out.println(encode);

        ModbusDeviceLog logDecode = ModbusDeviceLog.decode(encode);
        System.out.println(logDecode);

    }

    public static ModbusDeviceLog decode(List<Short> data) {
        ModbusDeviceLog log = new ModbusDeviceLog();
        log.setLogId(((data.get(0) & 0xffff) << 16) | (data.get(1) & 0xffff));
        log.setDeviceId(((data.get(2) & 0xffff) << 16) | (data.get(3) & 0xffff));
        log.setGatewayId(((data.get(4) & 0xffff) << 16) | (data.get(5) & 0xffff));
        log.setErrorId(((data.get(6) & 0xffff) << 16) | (data.get(7) & 0xffff));
        log.setUpdateDate(((data.get(8) & 0xffff) << 16) | (data.get(9) & 0xffff));
        return log;
    }
}
